package com.smartleanx.module.hrm.service.sms;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.smartleanx.framework.common.enums.BizTypeEnum;
import com.smartleanx.framework.common.pojo.PageResult;
import com.smartleanx.framework.common.util.collection.CollectionUtils;
import com.smartleanx.framework.common.util.json.JsonUtils;
import com.smartleanx.framework.common.util.object.BeanUtils;
import com.smartleanx.framework.customfield.core.service.CustomFieldDataService;
import com.smartleanx.framework.customfield.core.service.bo.CustomFieldDataSaveBO;
import com.smartleanx.framework.customfield.core.service.bo.inner.CustomFieldDataBaseBO;
import com.smartleanx.module.hrm.context.EmployeeContextHolder;
import com.smartleanx.module.hrm.controller.app.salarynotice.vo.AppSalaryNoticePageReqVO;
import com.smartleanx.module.hrm.controller.app.salarynotice.vo.AppSalaryNoticeSaveReqVO;
import com.smartleanx.module.hrm.dal.dataobject.employee.EmployeeDO;
import com.smartleanx.module.hrm.dal.dataobject.salarynotice.SalaryNoticeDO;
import com.smartleanx.module.hrm.dal.mysql.salarynotice.SalaryNoticeMapper;
import com.smartleanx.module.hrm.intergration.NotifyMessageSendProvider;
import com.smartleanx.module.hrm.intergration.NotifyMessageServiceProvider;
import com.smartleanx.module.hrm.service.employee.EmployeeService;
import com.smartleanx.module.hrm.service.esign.eums.ActorTypeEnum;
import com.smartleanx.module.hrm.service.esign.service.HrmEContractTaskActorsService;
import com.smartleanx.module.hrm.service.esign.service.HrmEContractTaskService;
import com.smartleanx.module.hrm.service.esign.temp.po.HrmEContractTask;
import com.smartleanx.module.hrm.service.esign.temp.po.HrmEContractTaskActors;
import com.smartleanx.module.hrm.service.instation.InStationSmsService;
import com.smartleanx.module.hrm.service.instation.InstationSmsTypeEnum;
import com.smartleanx.module.hrm.service.payroll.PayrollDetailService;
import com.smartleanx.module.hrm.service.salarynotice.SalaryNoticeService;
import com.smartleanx.module.hrm.service.salarynotice.bo.SalaryNoticeSaveBO;
import com.smartleanx.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import com.smartleanx.module.system.enums.customfield.CustomFieldLabelEnum;
import com.smartleanx.module.system.enums.notify.NotifyDetailTypeEnum;
import com.smartleanx.module.system.enums.notify.NotifyTemplateCodeEnum;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.smartleanx.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.smartleanx.module.hrm.enums.ErrorCodeConstants.*;


@Service
public class SmsServiceImpl implements SmsService {
//    @Autowired
//    private AsyncClient asyncClient;

    @Autowired
    private InStationSmsService inStationSmsService;
    @Autowired
    private HrmEContractTaskActorsService hrmEContractTaskActorsService;
    @Autowired
    private HrmEContractTaskService hrmEContractTaskService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private NotifyMessageSendProvider notifyMessageSendProvider;

    @Override
    public void sendSignSms(String sendPhone,String tempCode,JSONObject jsonObject) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId("LTAI5t9ajZe9Ju5CMsPF7nLB")
                .accessKeySecret("vxBdh7XihzwlPT1cwa7qv6bbSpd6aU")
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou")
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(sendPhone)
                .signName("青岛劳安智心科技有限公司")
                .templateCode(tempCode)
                .templateParam(jsonObject.toString())
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
            System.out.println(new Gson().toJson(resp));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        client.close();
    }

    @Override
    public void sendFillInsationAndSms(Long taskId, String type) {
        try{
            //1.站内信
            HrmEContractTask hrmEContractTask = hrmEContractTaskService.getById(taskId);
            List<HrmEContractTaskActors> taskActorsList = hrmEContractTaskActorsService.getTaskActorListByTaskId(taskId);
            Map<String, HrmEContractTaskActors> map = taskActorsList.stream().collect(Collectors.toMap(HrmEContractTaskActors::getActorType, Function.identity()));
            HrmEContractTaskActors corpActor = map.get(ActorTypeEnum.CORP.getCode());
            HrmEContractTaskActors personActor = map.get(ActorTypeEnum.PERSON.getCode());


            NotifySendSingleToUserReqDTO notifySendSingleToUserReqDTO = new NotifySendSingleToUserReqDTO();
            EmployeeDO employee = employeeService.getEmployeeById(corpActor.getEmpId());
            notifySendSingleToUserReqDTO.setUserId(employee.getUserId());
            notifySendSingleToUserReqDTO.setTemplateCode(type);
            notifySendSingleToUserReqDTO.setType(2);
            notifySendSingleToUserReqDTO.setTemplateParams(InstationSmsTypeEnum.getMapParam(personActor.getActorName(),hrmEContractTask.getContractName(), DateUtil.format(hrmEContractTask.getEffectiveDuration(), DatePattern.NORM_DATETIME_FORMAT),type));
            notifyMessageSendProvider.sendSingleNotify(notifySendSingleToUserReqDTO);

            //2. 短信
            HrmEContractTaskActors personTaskActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.PERSON.getCode());
            HrmEContractTaskActors corpTaskActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.CORP.getCode());
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("name",personTaskActor.getActorName());
            jsonObject.set("contractName",hrmEContractTask.getContractName());
            jsonObject.set("code",0);
            sendSignSms(corpTaskActor.getPsnAccount(),SmsTempEnum.EXPIRED_FILLIN_SYSTEM.getCode(),jsonObject);
        }catch (Exception e){
            System.out.println(e);
        }
    }

    @Override
    public void sendRefuseInsationAndSms(Long taskId, String type) {
        try{
            //1.站内信
            HrmEContractTask hrmEContractTask = hrmEContractTaskService.getById(taskId);
            List<HrmEContractTaskActors> taskActorsList = hrmEContractTaskActorsService.getTaskActorListByTaskId(taskId);
            Map<String, HrmEContractTaskActors> map = taskActorsList.stream().collect(Collectors.toMap(HrmEContractTaskActors::getActorType, Function.identity()));
            HrmEContractTaskActors corpActor = map.get(ActorTypeEnum.CORP.getCode());
            HrmEContractTaskActors personActor = map.get(ActorTypeEnum.PERSON.getCode());


            NotifySendSingleToUserReqDTO notifySendSingleToUserReqDTO = new NotifySendSingleToUserReqDTO();
            EmployeeDO employee = employeeService.getEmployeeById(corpActor.getEmpId());
            notifySendSingleToUserReqDTO.setUserId(employee.getUserId());
            notifySendSingleToUserReqDTO.setTemplateCode(type);
            notifySendSingleToUserReqDTO.setType(2);
            notifySendSingleToUserReqDTO.setTemplateParams(InstationSmsTypeEnum.getMapParam(personActor.getActorName(),hrmEContractTask.getContractName(), DateUtil.format(hrmEContractTask.getEffectiveDuration(), DatePattern.NORM_DATETIME_FORMAT),type));
            notifyMessageSendProvider.sendSingleNotify(notifySendSingleToUserReqDTO);

            //2. 短信
            HrmEContractTaskActors personTaskActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.PERSON.getCode());
            HrmEContractTaskActors corpTaskActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.CORP.getCode());
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("name",personTaskActor.getActorName());
            jsonObject.set("contractName",hrmEContractTask.getContractName());
            jsonObject.set("code",0);
            sendSignSms(corpTaskActor.getPsnAccount(),SmsTempEnum.EXPIRED_REFUSE_SYSTEM.getCode(),jsonObject);
        }catch (Exception e){
            System.out.println(e);
        }
    }

}